#include "showpicture.h"

#include <QPainter>
#include <QMouseEvent>
#include <QGraphicsDropShadowEffect>
#include <iostream>
#include <QTextStream>
#ifdef Q_OS_LINUX

#include <X11/Xlib.h>

#include <QX11Info>

#endif


#include <QDebug>

CShowPicture::CShowPicture(const QPixmap &pic, QWidget *parent)
    : QWidget(parent)
    , m_bMousePress(false)
    , m_MovePoint(0, 0)
    , m_Picture(pic)
{
    init();
}

CShowPicture::~CShowPicture()
{

}

void CShowPicture::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.save();
    painter.setRenderHints(QPainter::Antialiasing);

    painter.drawPixmap(this->rect(), m_Picture);
    painter.restore();
    painter.save();
    QPen pen = painter.pen();
    pen.setColor(QColor(0, 0, 255));
    pen.setWidth(1);
    painter.setPen(pen);
    painter.drawRect(QRect(rect().adjusted(0, 0, -1, -1)));

    QWidget::paintEvent(event);
}

void CShowPicture::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        m_bMousePress = true;
        m_MovePoint = event->globalPos() - /*pos()*/frameGeometry().topLeft();;
    }
    QWidget::mousePressEvent(event);
}

void CShowPicture::mouseReleaseEvent(QMouseEvent *event)
{
    m_bMousePress = false;
    QWidget::mouseReleaseEvent(event);
}

void CShowPicture::mouseMoveEvent(QMouseEvent *event)
{
    if(m_bMousePress)
    {
        QPoint movePos = event->globalPos();
#ifdef Q_OS_LINUX
        XEvent event;
        memset(&event, 0, sizeof(XEvent));

        Display *display = QX11Info::display();
        event.xclient.type = ClientMessage;
        event.xclient.message_type = XInternAtom(display, "_NET_WM_MOVERESIZE", False);
        event.xclient.display = display;
        //wid 是当前程序的 window id，可以通过 QWidget->wId()获得，QWidget 必须实例化
        event.xclient.window = (XID)(winId());
        event.xclient.format = 32;
        event.xclient.data.l[0] = movePos.x();
        event.xclient.data.l[1] = movePos.y();
        event.xclient.data.l[2] = 8;
        event.xclient.data.l[3] = Button1;
        event.xclient.data.l[4] = 1;

        XUngrabPointer(display, CurrentTime);
        XSendEvent(display,
                   QX11Info::appRootWindow(QX11Info::appScreen()),
                   False,
                   SubstructureNotifyMask | SubstructureRedirectMask,
                   &event);
        XFlush(display);
#else
        move(movePos - m_MovePoint);

#endif
    }
    QWidget::mouseMoveEvent(event);
}

void CShowPicture::keyPressEvent(QKeyEvent *event)
{
    switch(event->key())
    {
    case Qt::Key_Escape:
        close();
        break;
    default:
        QWidget::keyPressEvent(event);
    }
}

void CShowPicture::init()
{
    setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground);
    setAttribute(Qt::WA_DeleteOnClose);
    setAttribute(Qt::WA_QuitOnClose, false);
    this->resize(m_Picture.size());
}
